package com.t2t.top.framework.diamond;

import com.taobao.diamond.manager.DiamondManager;
import com.taobao.diamond.manager.ManagerListener;
import com.taobao.diamond.manager.impl.DefaultDiamondManager;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by yangpengfei on 2016/2/5.
 */
public class ConfigFactory {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    //配置中心-Group
    public static final String GROUP_KEY = "com.gome.top_topj";

    //配置中心-DataId
    public static final String DATA_ID_COMMONS = "jdbc";

    //单例对象
    private static ConfigFactory factory;

    //公共配置
    private Properties localConfig = new Properties();

    public synchronized static ConfigFactory getFactory() {
        if (factory == null) {
            factory = new ConfigFactory();
        }
        return factory;
    }

    /**
     * 重新构造缓存配置
     */
    public void rebuidConfig(String configInfo) {
        if (StringUtils.isBlank(configInfo)) {
            return;
        }

        logger.info("start config:{} ", configInfo);

        ReentrantLock lock = new ReentrantLock();
        InputStream in = null;
        try {
            in = new ByteArrayInputStream(configInfo.getBytes("UTF-8"));
            lock.lock();
            Properties temp = new Properties();
            temp.load(new InputStreamReader(in, "UTF-8"));
            setLocalConfig(temp);
        } catch (Exception e) {
            logger.info("读取diamond失败", e);
        } finally {
            try {
                if (in != null)
                    in.close();
            } catch (Exception e) {
                logger.error("关闭失败", e);
            }
            lock.unlock();
        }
    }

    public Properties getLocalConfig() {
        return localConfig;
    }

    public void setLocalConfig(Properties localConfig) {
        this.localConfig = localConfig;
    }

    public static String getString(String name, String... value) {
        String s = ConfigFactory.getFactory().getLocalConfig().getProperty(name);
        if (s == null) {
            return (value.length > 0) ? value[0] : null;
        }
        s = s.trim().replace(" ", "");
        return s;
    }

    public static String getString(ConfigOption option) {
        String s = ConfigFactory.getFactory().getLocalConfig().getProperty(option.getKey());
        if (s == null) {
            return option.getDefaultValue();
        }
        s = s.trim().replace(" ", "");
        return s;
    }

    public static String[] getStrings(String name, String... values) {
        String s = ConfigFactory.getFactory().getLocalConfig().getProperty(name);
        if (s == null) {
            return values;
        }
        s = s.trim().replace(" ", "");
        return s.split(",");
    }

    private ConfigFactory() {
        DiamondManager manager = new DefaultDiamondManager(GROUP_KEY, DATA_ID_COMMONS, new ManagerListener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String configInfo) {
                logger.info("changed config: " + configInfo);
                rebuidConfig(configInfo);
            }
        });
        manager.getDiamondConfigure().setPort(80);//设置diamond-server服务的端口
        rebuidConfig(manager.getAvailableConfigureInfomation(5000));
    }
}
